home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / util / urllib2_file.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  6KB  |  234 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from urllib2 import URLError
  5. from urllib import splittype
  6. from urllib import splithost
  7. from httplib import NotConnected
  8. from urllib import addinfourl
  9. import os
  10. import socket
  11. import sys
  12. import stat
  13. import mimetypes
  14. import mimetools
  15. import httplib
  16. import urllib
  17. import urllib2
  18. CHUNK_SIZE = 65536
  19.  
  20. def get_content_type(filename):
  21.     if not mimetypes.guess_type(filename)[0]:
  22.         pass
  23.     return 'application/octet-stream'
  24.  
  25.  
  26. def send_data(v_vars, v_files, boundary, sendfunc = None):
  27.     l = 0
  28.     for k, v in v_vars:
  29.         buffer = ''
  30.         buffer += '--%s\r\n' % boundary
  31.         buffer += 'Content-Disposition: form-data; name="%s"\r\n' % k
  32.         buffer += '\r\n'
  33.         buffer += v + '\r\n'
  34.         if sendfunc:
  35.             sendfunc(buffer)
  36.         
  37.         l += len(buffer)
  38.     
  39.     for k, v in v_files:
  40.         fd = v
  41.         if hasattr(fd, 'len'):
  42.             file_size = fd.len
  43.         else:
  44.             file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
  45.         if isinstance(k, tuple):
  46.             (k, name) = k
  47.         else:
  48.             name = fd.name.split('/')[-1]
  49.         if isinstance(name, unicode):
  50.             name = name.encode('UTF-8')
  51.         
  52.         buffer = ''
  53.         buffer += '--%s\r\n' % boundary
  54.         buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (k, name)
  55.         buffer += 'Content-Type: %s\r\n' % get_content_type(name)
  56.         buffer += 'Content-Length: %s\r\n' % file_size
  57.         buffer += '\r\n'
  58.         l += len(buffer)
  59.         if sendfunc:
  60.             sendfunc(buffer)
  61.             if hasattr(fd, 'seek'):
  62.                 fd.seek(0)
  63.             
  64.             while True:
  65.                 chunk = fd.read(CHUNK_SIZE)
  66.                 if not chunk:
  67.                     break
  68.                 
  69.                 sendfunc(chunk)
  70.         
  71.         l += file_size
  72.     
  73.     buffer = '\r\n'
  74.     buffer += '--%s--\r\n' % boundary
  75.     buffer += '\r\n'
  76.     if sendfunc:
  77.         sendfunc(buffer)
  78.     
  79.     l += len(buffer)
  80.     return l
  81.  
  82.  
  83. def do_request_(self, request):
  84.     host = request.get_host()
  85.     if not host:
  86.         raise URLError('no host given')
  87.     
  88.     data = request.get_data()
  89.     v_files = []
  90.     v_vars = []
  91.     if request.has_data() and not isinstance(data, str):
  92.         if hasattr(data, 'items'):
  93.             data = data.items()
  94.         else:
  95.             
  96.             try:
  97.                 if len(data) and not isinstance(data[0], tuple):
  98.                     raise TypeError
  99.             except TypeError:
  100.                 (_ty, _va, tb) = sys.exc_info()
  101.                 raise TypeError, 'not a valid non-string sequence or mapping object: %r' % type(data), tb
  102.  
  103.         for k, v in data:
  104.             if hasattr(v, 'read'):
  105.                 v_files.append((k, v))
  106.                 continue
  107.             v_vars.append((k, v))
  108.         
  109.         boundary = mimetools.choose_boundary()
  110.         request.boundary = boundary
  111.         request.v_files = v_files
  112.         request.v_vars = v_vars
  113.     
  114.     if len(v_vars) > 0 and len(v_files) == 0:
  115.         request.data = data = urllib.urlencode(v_vars)
  116.         v_files[:] = []
  117.         v_vars[:] = []
  118.     
  119.     if request.has_data():
  120.         if 'Content-type' not in request.headers:
  121.             if len(v_files) > 0:
  122.                 l = send_data(v_vars, v_files, boundary)
  123.                 request.add_unredirected_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
  124.                 request.add_unredirected_header('Content-length', str(l))
  125.             else:
  126.                 request.add_unredirected_header('Content-type', 'application/x-www-form-urlencoded')
  127.                 if 'Content-length' not in request.headers:
  128.                     request.add_unredirected_header('Content-length', '%d' % len(data))
  129.                 
  130.         
  131.     
  132.     (_scheme, sel) = splittype(request.get_selector())
  133.     (sel_host, _sel_path) = splithost(sel)
  134.     if not request.has_header('Host'):
  135.         if not sel_host:
  136.             pass
  137.         request.add_unredirected_header('Host', host)
  138.     
  139.     for name, value in self.parent.addheaders:
  140.         name = name.capitalize()
  141.         if not request.has_header(name):
  142.             request.add_unredirected_header(name, value)
  143.             continue
  144.     
  145.     return request
  146.  
  147. urllib2.AbstractHTTPHandler.do_request_ = do_request_
  148. old_open = urllib2.AbstractHTTPHandler.do_open
  149.  
  150. def do_open(self, http_class, req):
  151.     req = do_request_(self, req)
  152.     host = req.get_host()
  153.     if not host:
  154.         raise URLError('no host given')
  155.     
  156.     h = http_class(host)
  157.     h.set_debuglevel(self._debuglevel)
  158.     headers = dict(req.headers)
  159.     headers.update(req.unredirected_hdrs)
  160.     headers['Connection'] = 'close'
  161.     headers = dict((lambda .0: for name, val in .0:
  162. (name.title(), val))(headers.items()))
  163.     if req.has_data() and not isinstance(req.data, str):
  164.         reqdata = req
  165.     else:
  166.         reqdata = req.data
  167.     
  168.     try:
  169.         h.request(req.get_method(), req.get_selector(), reqdata, headers)
  170.         r = h.getresponse()
  171.     except socket.error:
  172.         err = None
  173.         raise URLError(err)
  174.  
  175.     r.recv = r.read
  176.     fp = socket._fileobject(r, close = True)
  177.     resp = addinfourl(fp, r.msg, req.get_full_url())
  178.     resp.code = r.status
  179.     resp.msg = r.reason
  180.     return resp
  181.  
  182. urllib2.AbstractHTTPHandler.do_open = do_open
  183.  
  184. def _send_request(self, method, url, body, headers):
  185.     header_names = []([ k.lower() for k in headers ])
  186.     skips = { }
  187.     if 'accept-encoding' in header_names:
  188.         skips['skip_accept_encoding'] = 1
  189.     
  190.     self.putrequest(method, url, **skips)
  191.     if isinstance(body, str):
  192.         if body and 'content-length' not in header_names:
  193.             self.putheader('Content-Length', str(len(body)))
  194.         
  195.     
  196.     for hdr, value in headers.iteritems():
  197.         self.putheader(hdr, value)
  198.     
  199.     self.endheaders()
  200.     if body:
  201.         self.send(body)
  202.     
  203.  
  204. httplib.HTTPConnection._send_request = _send_request
  205.  
  206. def send(self, str):
  207.     if self.sock is None:
  208.         if self.auto_open:
  209.             self.connect()
  210.         else:
  211.             raise NotConnected()
  212.     
  213.     if self.debuglevel > 0:
  214.         print 'send:', repr(str)
  215.     
  216.     
  217.     try:
  218.         if hasattr(str, 'boundary'):
  219.             boundary = str.boundary
  220.             v_files = str.v_files
  221.             v_vars = str.v_vars
  222.             send_data(v_vars, v_files, boundary, self.sock.sendall)
  223.         else:
  224.             self.sock.sendall(str)
  225.     except socket.error:
  226.         v = None
  227.         if v[0] == 32:
  228.             self.close()
  229.         
  230.         raise 
  231.  
  232.  
  233. httplib.HTTPConnection.send = send
  234.